package stats

import (
	"gitee.com/saxon134/sysmain/db"
	"gitee.com/saxon134/sysmain/db/models"
	"gitee.com/saxon134/sysmain/errs"
	"github.com/saxon134/go-utils/saData"
	"github.com/saxon134/go-utils/saData/saHit"
	"github.com/saxon134/go-utils/saData/saTime"
	"github.com/saxon134/go-utils/saLog"
	"sync"
	"time"
)

var _calls sync.Map

type api struct {
	success int
	fail    int
	t       int64
	syncing bool
}

type ApiRequest struct {
	Key     string
	App     string //必传
	Host    string //必传
	Port    int    //必传
	Path    string //必传
	Success bool   //默认false
}

// ApiCalls 统计接口调用情况
func ApiCalls(in *ApiRequest) {
	if _client == nil || in == nil {
		return
	}

	if in.App == "" || in.Path == "" || in.Host == "" || in.Port <= 0 {
		return
	}

	var key = in.Key + in.App + in.Host + saData.String(in.Port) + in.Path + saHit.Str(in.Success, "1", "0")
	var obj api

	v, ok := _calls.Load(key)
	if ok == false || v == nil {
		obj = api{}
	} else {
		obj, _ = v.(api)
	}

	if in.Success {
		obj.success++
	} else {
		obj.fail++
	}

	var now = time.Now()
	var ts = saTime.TimeToStr(now, saTime.FormatYMDHimple)
	if obj.syncing == false && (now.Unix()-obj.t > 10 || obj.success > 30000 || obj.fail > 30000) {
		obj.syncing = true
		obj.t = now.Unix()

		value := new(models.TblStatsApi)
		query := db.MySql.Table(models.TBNStatsApi).Where("ts = ?", ts)
		if key != "" {
			query.Where("`key` = ?", key)
		}
		query.Where("app = ?", in.App).
			Where("host = ?", in.Host).Where("port = ?", in.Port).
			Where("path = ?", in.Path)
		query.First(value)

		if value.Id <= 0 {
			value.Ts = saData.Int64(ts)
			value.Success = 0
			value.Fail = 0

			value.Key = in.Key
			value.App = in.App
			value.Host = in.Host
			value.Port = in.Port
			value.Path = in.Path
		}

		value.Success += obj.success
		value.Fail += obj.fail
		err := db.MySql.Save(value).Error
		if err != nil {
			saLog.Err(errs.New(err))
		}

		obj.syncing = false
		obj.t = now.Unix()
		obj.success = 0
		obj.fail = 0
	}
	_calls.Store(key, obj)
}
